from flask import Flask, make_response, jsonify, g, current_app as app,Blueprint,request
from sqlalchemy import select,insert,update,func,join
from sqlalchemy.sql import text
from eim.tools.dbtool import DBTool
from eim import db
from eim.tools.searchtool import SearchCondition,SearchConditionList,MatchLogic,PartnerRS
from eim.result.simple_result import SimpleResult

prjbp=Blueprint("prjbp","prjbp",__name__,url_prefix="/project")

@prjbp.route("/append",methods=["PUT"])
def appendNewProject():
    """
    添加新的项目信息
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("参数类型必须为json")
        
        pks = pms.keys()
        if('pnumber' not in pks) or ('pname' not in pks) or ('pcomment' not in pks) :
            raise Exception("缺少必要的参数")
        
        from eim.Services.projectService import ProjectService
        prjservice = ProjectService(db)
        id =prjservice.appendProject(pms["pname"],pms["pnumber"],pms["pcomment"])
        return SimpleResult(status="T",value=id).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    

@prjbp.route("/upgrade/<int:id>",methods=["POST"])
def updateProject(id:int):
    """
    更新指定ID的项目信息

    Args:
        id (int): 项目ID
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("参数类型必须为json")
        
        pks = pms.keys()
        if(len(pks)<1):
            raise Exception("缺少必要的参数")
        
        if('pcode' in pks):
            raise Exception("项目编码不能修改")
    
            
        
        from eim.Services.projectService import ProjectService
        prjservice = ProjectService(db)
        
        cnt=prjservice.updateProject(id,pms)
        return SimpleResult(status='T',value=cnt).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()


@prjbp.route("/getPrjByPnumber/<pnumber>",methods=["GET"])    
def getProjectByPnumber(pnumber:str):
    """
    根据项目手工编号获取项目信息

    Args:
        pnumber (str): 项目手工编号
    """
    try:
        from eim.Services.projectService import ProjectService
        ps = ProjectService(db)
        pj= ps.getPrjByPnumber(pnumber)
        return SimpleResult(status='T',value=pj).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@prjbp.route("/treeproject",methods=["GET"])
def treeProject():
    """
    获取项目的树形结构
    """
    try:
        from eim.Services.projectService import ProjectService
        ps = ProjectService(db)
        rootnode={}
        prtcode=''
        tree=ps.projectTree(prtcode,rootnode)
        return SimpleResult(status='T',value=tree).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@prjbp.route("/pageProject/<int:pn>/<int:ps>",methods=["POST"])
def pageProject(pn:int,ps:int):
    """
    分页检索项目信息

    Args:
        pn (int): 分页页码
        ps (int): 分页页码尺寸
    """
    try:
        pms = request.json
        if(not isinstance(pms,dict)):
            raise Exception("提交的检索参数格式不正确")
        keys = pms.keys()
        if('cols' not in keys):
            raise Exception("查询对象缺少字段列表")
        if('pms' not in keys):
            raise Exception("缺少查询条件")
        
        slist = SearchConditionList()
        for item in pms['pms']:
            cd = item["CD"]
            cdobj = SearchCondition(cd["field"],MatchLogic.from_Name(cd["logic"]),cd["value"])
            rs=PartnerRS.from_name(item["RS"])
            slist.appendCondition(rs,cdobj)
        
        from eim.Services.projectService import ProjectService
        prjobj = ProjectService(db)
        fields = pms["cols"]
        res = prjobj.pageProject(pn,ps,fields,slist)
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()
    
@prjbp.route("/delproject/<int:id>",methods=["DELETE"])
def deleteProject(id:int):
    """
    删除指定id的项目信息

    Args:
        id (int): 待删除的项目ID
    """
    try:
        from eim.Services.projectService import ProjectService
        prjobj = ProjectService(db)
        res = prjobj.deleteByID(id)
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@prjbp.route("/getLookUpData",methods=["GET"])
def getProjectLoopupData():
    """
    获取project的lookup数据
    """
    try:
        from eim.Services.projectService import ProjectService
        prjobj = ProjectService(db)
        res = prjobj.getPrjLoopupData()
        return SimpleResult(status='T',value=res).toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(es)
        return SimpleResult(msg=info).toDict()
 
@prjbp.route("/batchActiveProjects",methods=["POST"])   
def batchActiveProjects():
    """
    批量激活项目
    """
    try:
        from eim.Services.projectService import ProjectService
        prjobj = ProjectService(db)
        pms = request.json
        if(not isinstance(pms['ids'],list)):
            raise Exception("ids参数必须为list")
        vls = {
            "status":"01"
        }
        for id in pms['ids']:
            prjobj.updateProject(id,vls)
        return SimpleResult(status="T",value="").toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()

@prjbp.route("/batchStopProjects",methods=["POST"])   
def batchStopProjects():
    """
    批量停用项目
    """
    try:
        from eim.Services.projectService import ProjectService
        prjobj = ProjectService(db)
        pms = request.json
        if(not isinstance(pms['ids'],list)):
            raise Exception("ids参数必须为list")
        vls = {
            "status":"00"
        }
        for id in pms['ids']:
            prjobj.updateProject(id,vls)
        return SimpleResult(status="T",value="").toDict()
    except Exception as es:
        info = str(es)
        app.logger.error(info)
        return SimpleResult(msg=info).toDict()